exports.__esModule = true;

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

exports.default = class extends think.Service {
    constructor() {
        super();
        const db = this.db;
        this.userModel = db['sys_user'];
        this.orgModel = db['sys_org'];
        this.roleUserModel = db['sys_role_user'];
        this.postModel = db['sys_post'];
        this.userPostModel = db['sys_user_post'];
        this.defData = {
            userid: '000000',
            roleid: '000000'
        };
        this.userModel.belongsTo(this.orgModel, {
            foreignKey: 'org_id',
            targetKey: 'id'
        });
        this.userModel.belongsToMany(this.postModel, {
            through: this.userPostModel, foreignKey: 'user_id', otherKey: 'post_id'
        });
        this.postModel.belongsToMany(this.userModel, {
            through: this.userPostModel, foreignKey: 'post_id', otherKey: 'user_id'
        });
    }

    /**
     * 获取用户个人资料
     * by userid
     */
    getUserInfo(data) {
        var _this = this;

        return _asyncToGenerator(function* () {
            try {
                const condition = `select a.*,b.org_name,c.realname as create_name,
                DATE_FORMAT(a.create_date,'%Y-%m-%d %H:%i') as createdate from sys_user a 
                left join sys_org b on b.id = a.org_id 
                left join sys_user c on c.id = a.create_by 
                where a.id='${data.id}'`;
                const userInfos = yield _this.CrudService.querySql(condition);
                if (userInfos.length > 0) {
                    let userinfo = userInfos[0];
                    userinfo.userPostList = [];
                    const userPostList = yield _this.postModel.findAll({
                        include: [{ model: _this.userModel, where: { id: data.id }, attributes: [] }],
                        attributes: ['post_name']
                    });
                    if (userPostList.length > 0) {
                        userinfo.userPostList = userPostList.map(function (item) {
                            return item.post_name;
                        });
                    }
                    return userinfo;
                } else {
                    return false;
                }
            } catch (err) {
                return _this.exceptionService.handleError(err);
            }
        })();
    }
    /**
     * 查询用户信息
     * @data
     * departid --部门id
     * username --用户名
     * realname --真实姓名
     * --------以上为条件查询--------
     * options --分页查询条件
     * options.page --页码 0开始
     * opations.pageSize --单页记录数
     * @return
     * flag --标识
     * count --记录总数
     * rows --当前页数据
     */
    getUserList(data) {
        var _this2 = this;

        return _asyncToGenerator(function* () {
            data.start = (parseInt(data.page) - 1) * parseInt(data.pageSize);
            const optJson = JSON.parse(data.options);
            const Op = _this2.db.Sequelize.Op;
            let where = {
                del_flag: 0,
                id: {
                    [Op.not]: '000000'
                }
            };
            if (!think.isEmpty(optJson)) {
                if (optJson.org_id && optJson.org_id.length > 0) {
                    where.org_id = {
                        [Op.in]: optJson.org_id
                    };
                }
                if (optJson.username) {
                    where.username = {
                        [Op.like]: '%' + optJson.username + '%'
                    };
                }
                if (optJson.realname) {
                    where.realname = {
                        [Op.like]: '%' + optJson.realname + '%'
                    };
                }
                if (optJson.phone) {
                    where.phone = {
                        [Op.like]: '%' + optJson.phone + '%'
                    };
                }
                if (optJson.status) {
                    where.status = optJson.status;
                }
            }
            try {
                const condition = {
                    where: where,
                    limit: parseInt(data.pageSize),
                    offset: parseInt(data.start),
                    include: [{
                        model: _this2.orgModel,
                        attributes: ['org_name']
                    }, {
                        model: _this2.postModel,
                        attributes: ['id', 'post_name']
                    }],
                    order: [['last_login_time', 'desc']],
                    distinct: true
                };
                return yield _this2.userModel.findAndCountAll(condition);
            } catch (err) {
                return _this2.exceptionService.handleError(err);
            }
        })();
    }

    /**
     * 查询所有用户
     * @data
     */
    getAllUser() {
        var _this3 = this;

        return _asyncToGenerator(function* () {
            try {
                return yield _this3.userModel.findAll();
            } catch (err) {
                return _this3.exceptionService.handleError(err);
            }
        })();
    }
    /**
     * 保存用户信息 新增|编辑
     * @data 用户信息
     * @returns Boolean
     */
    saveUserInfo(data) {
        var _this4 = this;

        return _asyncToGenerator(function* () {
            const Op = _this4.db.Sequelize.Op;
            try {
                const oldUser = yield _this4.userModel.findOne({
                    where: {
                        [Op.or]: {
                            username: data.username,
                            phone: data.phone
                        }
                    },
                    attributes: ['id', 'username', 'phone']
                });
                if (data.id) {
                    if (oldUser && oldUser.id !== data.id) {
                        return false;
                    } else {
                        yield _this4.userModel.update(data, {
                            where: {
                                id: data.id
                            }
                        });
                    }
                } else {
                    if (oldUser) {
                        return false;
                    } else {
                        data.id = think.uuid('v1');
                        data.login_flag = 1; //默认激活
                        yield _this4.userModel.create(data);
                    }
                }
                return data.id;
            } catch (err) {
                return _this4.exceptionService.handleError(err);
            }
        })();
    }
    /**
     * 获取用户名列表
     */
    getUserName() {
        var _this5 = this;

        return _asyncToGenerator(function* () {
            const Op = _this5.db.Sequelize.Op;
            try {
                const user = yield _this5.userModel.findAll({
                    where: {
                        id: {
                            [Op.not]: _this5.defData.userid
                        }
                    },
                    attributes: ['id', 'username', 'realname']
                });
                return user;
            } catch (err) {
                return _this5.exceptionService.handleError(err);
            }
        })();
    }

    getUserInfoById(data) {
        var _this6 = this;

        return _asyncToGenerator(function* () {
            try {
                const user = yield _this6.userModel.findOne({
                    where: {
                        id: data.id
                    },
                    attributes: ['id', 'realname', 'pic_path']
                });
                return user;
            } catch (err) {
                return _this6.exceptionService.handleError(err);
            }
        })();
    }
    getUserInfoByIds(data) {
        var _this7 = this;

        return _asyncToGenerator(function* () {
            try {
                const Op = _this7.db.Sequelize.Op;
                const user = yield _this7.userModel.findAll({
                    where: {
                        id: {
                            [Op.in]: data.ids
                        }
                    },
                    attributes: ['id', ['realname', 'name']]
                });
                return user;
            } catch (error) {
                return _this7.exceptionService.handleError(error);
            }
        })();
    }
    /**
     * 删除用户信息
     * @data
     * data.id --删除用户id
     */
    delUserInfo(data) {
        var _this8 = this;

        return _asyncToGenerator(function* () {
            const Op = _this8.db.Sequelize.Op;
            // const userid = this.defData.userid; //系统用户id,现在写死的
            let where = {};
            try {
                // await this.userModel.update({
                //     del_flag: 1
                // }, {
                //     where: where
                // });
                // return true;
                if (typeof data.id === 'string') {
                    //单条删除
                    where = {
                        id: data.id
                    };
                } else {
                    //批量删除
                    where = {
                        id: {
                            [Op.in]: data.id
                        }
                    };
                }
                let deletestatus = yield _this8.userModel.destroy({ where: where });
                return deletestatus;
                // if (data.id === userid) {
                //     flag = false;
                // } else {
                //     await this.userModel.update({del_flag:1},{
                //         where: {
                //             id: data.id
                //         }
                //     });
                //     // await this.roleUserModel.destroy({
                //     //     where: {
                //     //         userid: data.id
                //     //     }
                //     // });
                //     // await this.userModel.destroy({
                //     //     where: {
                //     //         id: data.id
                //     //     }
                //     // });
                // }
                // return flag;
            } catch (err) {
                return _this8.exceptionService.handleError(err);
            }
        })();
    }
    /**
     * 验证旧密码
     * @data
     * data.username --用户名
     * data.password --用户密码 明文
     */
    checkPsd(data) {
        var _this9 = this;

        return _asyncToGenerator(function* () {
            data.password = think.irreversibleEncrypt(data.username, data.password);
            let flag = true;
            try {
                const count = yield _this9.userModel.count({
                    where: data
                });
                if (count === 0) {
                    flag = false;
                }
                return flag;
            } catch (err) {
                return _this9.exceptionService.handleError(err);
            }
        })();
    }

    /**********************用户管理页面与角色相关********************************* */
    /**
     * 保存用户角色关联
     */
    saveRoleUser(data) {
        var _this10 = this;

        return _asyncToGenerator(function* () {
            const Op = _this10.db.Sequelize.Op;
            let flag1 = true;
            let flag2 = true;
            try {
                if (data.delList.length > 0) {
                    const delRole = yield _this10.roleUserModel.destroy({
                        where: {
                            userid: data.userid,
                            roleid: {
                                [Op.in]: data.delList
                            }
                        }
                    });
                    if (!delRole) {
                        flag1 = false;
                    }
                }
                if (data.addList.length > 0) {
                    const addList = data.addList;
                    const dataArr = addList.map(function (d) {
                        const params = {
                            id: think.uuid('v1'),
                            userid: data.userid,
                            roleid: d
                        };
                        return params;
                    });
                    const addRole = yield _this10.roleUserModel.bulkCreate(dataArr);
                    if (!addRole) {
                        flag2 = false;
                    }
                }
                if (flag1 && flag2) {
                    return true;
                } else {
                    return false;
                }
            } catch (err) {
                return _this10.exceptionService.handleError(err);
            }
        })();
    }

};